import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home/index.vue'
import axios from 'axios';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home,
      children: [
        {
          // 默认图表展示为首页
          path: '',
          name: 'EchartsShow',
          component: () => import('@/views/EchartsShow/index.vue')
        },
        {
          path: '/dataShow',
          name: 'dataShow',
          component: () => import('@/views/DataShow/index.vue')
        },
        {
          path: '/goodsDetails/:id',
          name: 'goodsDetails',
          component: () => import('@/views/GoodsDetails/index.vue')
        },
        {
          path: '/cartShow',
          name: 'cartShow',
          component: () => import('@/views/CartShow/index.vue')
        },
        {
          path: '/manage',
          name: 'manage',
          component: () => import('@/views/Manage/index.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login/index.vue')
    }
  ],
})


// 验证 Token 是否有效
const validateToken = async () => {
  const token = localStorage.getItem('token');
  if (!token) return false;

  try {
    //验证 Token
    const response = await axios.post('/api/user/validate-token', { token });
    return response.data.valid;
  } catch (error) {
    console.error('Token 验证出错:', error);
    return false;
  }
};

// 导航前置守卫
router.beforeEach(async (to, from, next) => {
  const isLoggedIn = await validateToken();

  if (to.name === 'Login' && isLoggedIn) {
    // 如果用户已登录且要访问登录页，跳转到首页
    next({ name: 'home' });
  } else if (to.name !== 'Login' && !isLoggedIn) {
    // 如果用户未登录且要访问非登录页，跳转到登录页
    next({ name: 'Login' });
  } else {
    // 其他情况正常放行
    next();
  }
});


export default router
